<template>
	<xn-form-container title="调解协议上传" :width="400" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-row :gutter="24">
			<a-col :span="24">
				<a-spin :spinning="uploadLoading">
					<a-upload-dragger
						ref="uploadRef"
						before-upload="handleBeforeUpload"
						v-model:file-list="fileList"
						:show-upload-list="true"
						:headers="headers"
						accept=".xlsx, .xls, .csv"
						auto-upload="false"
						multiple
					>
						<p class="ant-upload-drag-icon">
							<inbox-outlined />
						</p>
						<p class="ant-upload-text">单击或拖动文件到此区域进行上传</p>
						<p class="ant-upload-hint">支持单个上传</p>
					</a-upload-dragger>
					<a-button type="link" @click="download">点击下载调解协议上传模版</a-button>
					<a-divider />
					<a-form class="mt-2" ref="formRef" :model="formData" :rules="rules" label-align="right">
						<a-row>
							<a-col :span="24">
								<a-form-item label="有效期" name="expiryDate">
									<a-date-picker
										v-model:value="formData.expiryDate"
										:disabled-date="disabledDate"
										placeholder="请选择有效期"
										style="width: 100%"
									/>
								</a-form-item>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-form-item label="调解中心" name="companyName">
									<a-select v-model:value="formData.configId" placeholder="请选择调解中心" @change="handleCenterChange">
										<a-select-option
											v-for="option in tjCenterList"
											:key="option.id"
											:value="option.id"
											:label="option.companyName"
										>
											{{ option.companyName }}
										</a-select-option>
									</a-select>
								</a-form-item>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-form-item label="微信公众号" name="weChatOfficialAccount">
									<a-input v-model:value="formData.weChatOfficialAccount" />
								</a-form-item>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-form-item label="省份简称" name="provAbbr">
									<a-input v-model:value="formData.provAbbr" />
								</a-form-item>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-form-item label="访问域名" name="officialWebsite">
									<a-input v-model:value="formData.officialWebsite" />
								</a-form-item>
							</a-col>
						</a-row>
						<a-row>
							<a-col :span="24">
								<a-form-item label="公章图片" name="officialSealUrl">
									<img
										v-if="formData.officialSealUrl"
										:src="formData.officialSealUrl"
										alt="公章图片"
										style="width: 100px"
									/>
								</a-form-item>
							</a-col>
						</a-row>
					</a-form>
				</a-spin>
			</a-col>
		</a-row>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import tool from '@/utils/tool'
	import fileApi from '@/api/tjzy/file/fileApi'
	import downloadUtil from '@/utils/downloadUtil'
	import mediationProtocolApi from '@/api/website/protocol/mediationProtocolApi'
	import configApi from '@/api/website/config/configApi'
	import { message } from 'ant-design-vue'
	import dayjs from 'dayjs'

	const emit = defineEmits({ successful: null })
	const headers = ref({
		token: tool.data.get('TOKEN')
	})
	const visible = ref(false)
	const tjCenterList = ref([])
	const uploadLoading = ref(false)
	const submitLoading = ref(false)
	const fileList = ref([])
	const uploadRef = ref()
	const formRef = ref()
	const formData = ref({
		expiryDate: '',
		configId: '',
		companyName: '',
		officialWebsite: '',
		officialSealUrl: ''
	})
	// 修改规则，去掉city相关规则
	const rules = {
		expiryDate: [{ required: true, message: '请选择有效期', trigger: 'change' }],
		configId: [{ required: true, message: '请选择调解中心', trigger: 'change' }],
		companyName: [{ required: true, message: '请选择调解中心', trigger: 'change' }],
		provAbbr: [{ required: true, message: '省份简称不能为空', trigger: 'blur' }],
		weChatOfficialAccount: [{ required: true, message: '微信公众号不能为空', trigger: 'blur' }],
		officialWebsite: [{ required: true, message: '访问域名不能为空', trigger: 'blur' }],
		officialSealUrl: [{ required: true, message: '公章图片 URL 不能为空', trigger: 'blur' }]
	}

	// 禁止选择今天之前的日期
	const disabledDate = (current) => {
		return current && current < dayjs().startOf('day')
	}

	const getLastDayOfMonth = () => {
		const now = new Date()
		return dayjs(new Date(now.getFullYear(), now.getMonth() + 1, 0))
	}

	// 打开抽屉
	const onOpen = () => {
		visible.value = true
		configApi.listAll().then((res) => {
			tjCenterList.value = res
		})
		formData.value.expiryDate = getLastDayOfMonth()
	}

	// 关闭抽屉
	const onClose = () => {
		visible.value = false
		// 重置弹框数据
		fileList.value = []
		formData.value = {
			companyName: '',
			weChatOfficialAccount: '',
			officialWebsite: '',
			officialSealUrl: ''
		}
		emit('successful')
	}

	const handleBeforeUpload = () => {
		return false
	}

	const handleCenterChange = (value) => {
		const selectedCenter = tjCenterList.value.find((item) => item.id === value)
		if (selectedCenter) {
			formData.value.companyName = selectedCenter.companyName
			formData.value.provAbbr = selectedCenter.provAbbr
			formData.value.weChatOfficialAccount = selectedCenter.weChatOfficialAccount
			formData.value.officialWebsite = selectedCenter.websiteUrl
			formData.value.officialSealUrl = selectedCenter.officialSealUrl
		}
	}

	const onSubmit = () => {
		if (fileList.value.length === 0) {
			message.error('请先选择文件')
			return
		}
		formRef.value
			.validate()
			.then(() => {
				uploadLoading.value = true
				submitLoading.value = true
				formData.value.expiryDate = formData.value.expiryDate.format('YYYY-MM-DD')
				const fileData = new FormData()
				fileData.append('multipartFile', fileList.value[0].originFileObj)
				fileData.append(
					'mediationProtocolImportAddBo',
					new Blob([JSON.stringify(formData.value)], { type: 'application/json' })
				)
				// 确保传递公司名称和图片 URL
				mediationProtocolApi.importExcel(fileData).finally(() => {
					uploadLoading.value = false
					submitLoading.value = false
					onClose()
					emit('successful')
				})
			})
			.catch(() => {
				console.log('表单验证失败')
			})
	}

	const download = () => {
		fileApi.downloadWithBucket('gzx-excel-template', '官网调解协议上传模版.xlsx').then((res) => {
			downloadUtil.resultDownload(res)
		})
	}

	defineExpose({
		onOpen
	})
</script>
